const router = require("koa-router")();
const UserBasicModel = require('../../model/UserBasic')
const UserProfileModel = require('../../model/UserProfile')
const UserCode = require('../../model/UserCode')
const { createTokenByUserId, createNewTokenByContext } = require('../token')
const UUID = require('uuid')

// 登录或者注册
router.post('/', async (ctx, next) => {
  const { mobile, code  } = ctx.request.body   
  if (!mobile || !code) {
      return {  status: 400, success: false, message: '手机号或验证码不正确' }  
  }
  if (!/^1[3-9]\d{9}$/.test(mobile) || !/^\d{6}$/.test(code)) {
    return {  status: 400, success: false, message: '手机号或验证码格式不正确' }  
  } 
  if (code !==  '246810') {
   let  codeOne = await UserCode.findOne({ mobile, code }).lean()
   if (codeOne) {
      // 验证码要保证5分钟内有效
      const interval = (Date.now() - codeOne.timer) / 1000 - 300
      if (interval > 0) {
        return {  status: 400, success: false, message: '验证码已经超时或者失效' }  
      }
   }else {
    return {  status: 400, success: false, message: '验证码不正确' }  
   }
  }
  const person = await UserBasicModel.findOne({ mobile }).lean() // 当前人
  let data = null 
  if (person) {
    data = await createTokenByUserId(person.user_id) // 根据用户id创建新token
  }else {
   const user_id = UUID.v4()
   await UserBasicModel.create({ mobile, user_id, user_name: mobile })
   await UserProfileModel.create({ gender: 1, user_id, real_name: mobile, birthday: '1990-11-20' }) // 插入基本资料的表
   data = await createTokenByUserId(user_id) // 根据用户id创建新token
  }
  ctx.status = 201

  return  { data }
})
// token刷新
router.put('/', async (ctx, next) => {
  const token = await createNewTokenByContext(ctx)
  ctx.status = 201

  return {  data: { token } }
})
module.exports = router.routes()
